package edu.colorado.cs.correll.cudroplet.shaperecognition;

import java.util.HashSet;
import java.util.Set;
import java.util.Stack;

public class AlphaShapeCollection {

	public ShapeRecognition shapeRecognition;
	public Set<Circumcircle> allCircumcircles;
	public Set<Circumcircle> boundaryCircumcircles;
	public Set<AlphaShape> alphaShapes = new HashSet<AlphaShape>();

	private CircumcircleDictionary boundaryCircumcircleDictionary;

	public AlphaShapeCollection(ShapeRecognition shapeRecognition,
			Set<Circumcircle> allCircumcircles,
			Set<Circumcircle> boundaryCircumcircles) {
		this.shapeRecognition = shapeRecognition;
		this.allCircumcircles = allCircumcircles;
		this.boundaryCircumcircles = boundaryCircumcircles;

		boundaryCircumcircleDictionary = new CircumcircleDictionary(boundaryCircumcircles);
		
		// create alpha shapes
		for (Robot robot: boundaryCircumcircleDictionary.robotMap.keySet()) {
			robot.alphaLeader = null;
		}

		// create alpha shapes
		for (Robot robot: boundaryCircumcircleDictionary.robotMap.keySet()) {
			if (robot.alphaLeader == null) {
				alphaShapes.add(getAlphaShape(robot));
			}
		}
	}

	/**
	 * Calculate the subgraph
	 */
	AlphaShape getAlphaShape(Robot root) {
		Leader leader = new Leader();
		Set<Robot> robotSet = new HashSet<Robot>();
		Stack<Robot> stack = new Stack<Robot>();
		// set the leader when adding to queue
		root.alphaLeader = leader;
		stack.push(root);
		robotSet.add(root);
		while (!stack.empty()) {
			Robot robot = stack.pop();
			Set<Robot> neighbors = boundaryCircumcircleDictionary.robotMap.get(robot);
			for (Robot r : neighbors) {
				if (!robotSet.contains(r)) {
					r.alphaLeader = leader;
					stack.push(r);
					robotSet.add(r);
				}
			}
		}
		Set<Circumcircle> circumcircles = new HashSet<Circumcircle>();
		for(Robot r: robotSet) {
			circumcircles.addAll(boundaryCircumcircleDictionary.circumcircleMap.get(r));
		}
		return new AlphaShape(shapeRecognition, circumcircles, leader);
	}
}
